<?php

namespace core;

class mphp
{
    public static $classMap = array();

    public $assign;

    public static function run()
    {
        date_default_timezone_set("PRC");
        \core\lib\log::init();
        $route = new \core\lib\route();
        $controllerClass = $route->controller;
        $action = $route->action;
        $controllerFile = APP . '/controllers/' . $controllerClass . 'Controller.php';
        $ctrlClass = '\\' . MODULE . '\controllers\\' . $controllerClass . 'Controller';
        if (is_file($controllerFile)) {
            include $controllerFile;
            $ctrl = new $ctrlClass();
            $ctrl->$action();
            \core\lib\log::log('controller:'.$controllerClass.' '.'action:'.$action);
        } else {
            throw new \Exception('找不到控制器'.$controllerClass);
        }
    }

    public static function load($class)
    {
        // 自动加载类库
        if (isset($classMap[$class])) {
            return true;
        } else {
            $class = str_replace('\\', '/', $class);
            $file = MPHP . '/' . $class . '.php';
            if (is_file($file)) {
                include $file;
                self::$classMap[$class] = $class;
            } else {
                return false;
            }
        }
    }

    public function assign($name, $value)
    {
        $this->assign[$name] = $value;
    }

    public function display($file)
    {
        $filePath = APP . '/views/' . $file;
        if (is_file($filePath)) {
//            extract($this->assign); // 未加载Twig框架前的代码
//            include $filePath; // 未加载Twig框架前的代码

            $loader = new \Twig\Loader\FilesystemLoader(APP . '/views');
            $twig = new \Twig\Environment($loader, array(
                'cache' => MPHP . '/log/twig',
                'debug' => DEBUG
            ));
            $template = $twig->load($file);
            $template->display($this->assign ? $this->assign : array());
        }
    }

}